package com.yang.aop;

import com.yang.utlis.log.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * 请求响应日志 AOP
 *
 * @author yanglingxiao
 **/
@Aspect
@Component
@Slf4j
public class LogInterceptor {

    /**
     * 执行拦截
     */
    @Around("execution(* com.yang.controller.*.*.*(..))")
    public Object doInterceptor(ProceedingJoinPoint point) throws Throwable {
        // 获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 生成请求唯一 id
        String requestId = UUID.randomUUID().toString();
        // 获取url
        String url = httpServletRequest.getRequestURI();
        // 获取ip
        String ip = IpUtils.getUserIP(httpServletRequest);
        // 获取请求参数
        Object[] args = point.getArgs();
        String reqParam = "[" + StringUtils.join(args, ", ") + "]";
        // 输出请求日志
        log.info("=============request start==============");
        log.info("id: {}, path: {}, ip: {}, params: {}, maximum memory: {}m, allocated memory: {}m, remain memory: {}m, maximum available memory: {}m"
                , requestId, url, ip, reqParam,
                Runtime.getRuntime().maxMemory() / 1024 / 1024,
                Runtime.getRuntime().totalMemory() / 1024 / 1024,
                Runtime.getRuntime().freeMemory() / 1024 / 1024,
                (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()) / 1024 / 1024);
        log.info("========================================");
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 执行原方法
        Object result = point.proceed();
        stopWatch.stop(); // 计时结束
        // 输出响应日志
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("=============request end==============");
        log.info("id: {}, cost: {}ms", requestId, totalTimeMillis);
        log.info("========================================");
        return result;
    }
}

